package cn.wgx.commons.storage.filetool;

import cn.wgx.commons.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class FileHeadType {
    private static Logger log = LoggerFactory.getLogger(FileHeadType.class);
    /**
     * 常用文件的文件头如下：(以前六位为准)
     * JPEG (jpg)，文件头：FFD8FF
     * PNG (png)，文件头：89504E47
     * GIF (gif)，文件头：47494638
     * TIFF (tif)，文件头：49492A00
     * Windows Bitmap (bmp)，文件头：424D
     * CAD (dwg)，文件头：41433130
     * Adobe Photoshop (psd)，文件头：38425053
     * Rich Text Format (rtf)，文件头：7B5C727466
     * XML (xml)，文件头：3C3F786D6C
     * HTML (html)，文件头：68746D6C3E
     * Email [thorough only] (eml)，文件头：44656C69766572792D646174653A
     * Outlook Express (dbx)，文件头：CFAD12FEC5FD746F
     * Outlook (pst)，文件头：2142444E
     * MS Word/Excel (xls.or.doc)，文件头：D0CF11E0
     * MS Access (mdb)，文件头：5374616E64617264204A
     * WordPerfect (wpd)，文件头：FF575043
     * Postscript (eps.or.ps)，文件头：252150532D41646F6265
     * Adobe Acrobat (pdf)，文件头：255044462D312E
     * Quicken (qdf)，文件头：AC9EBD8F
     * Windows Password (pwl)，文件头：E3828596
     * ZIP Archive (zip)，文件头：504B0304
     * RAR Archive (rar)，文件头：52617221
     * Wave (wav)，文件头：57415645
     * AVI (avi)，文件头：41564920
     * Real Audio (ram)，文件头：2E7261FD
     * Real Media (rm)，文件头：2E524D46
     * MPEG (mpg)，文件头：000001BA
     * MPEG (mpg)，文件头：000001B3
     * Quicktime (mov)，文件头：6D6F6F76
     * Windows Media (asf)，文件头：3026B2758E66CF11
     * MIDI (mid)，文件头：4D546864
     */
    private static Map<String,String> FILE_TYPE_MAP;

    private static String[] FILE_EXT_3D = {"max", "ma", "mb", "obj", "fbx", "ztl", "3ds", "c4d", "u3d",
                                            "blend","Lwo", "ZPR", "dwg", "vue", "Pz3", "step", "stp", "stl",
                                            "skp", "ige", "igs", "iges", "unitypackage"};
    private static String[] FILE_EXT_2D = {"jpg", "jpeg", "gif", "png" , "bmp", "swf"};
    private static String[] FILE_EXT_AUDIO = {"mp3", "m4a", "wav", "wma", "wav", "ogg", "ape", "acc" , "mid" };
    private static String[] FILE_EXT_VIDEO = {"mp4", "avi", "mpeg", "mpg", "mtv", "mov", "3gp", "amv",
                                                "flv", "dmv", "mpe", "mpa", "mkv", "rmvb", "rm"};
    private static String[] FILE_EXT_ZIP = {"zip", "7z"};
    private static String [][] ALL_EXT = {FILE_EXT_3D,FILE_EXT_2D, FILE_EXT_VIDEO,FILE_EXT_AUDIO};



    static {
        if(FILE_TYPE_MAP == null){
            FILE_TYPE_MAP = new HashMap<String,String>();
            FILE_TYPE_MAP.put("FFD8FF","jpg");
            FILE_TYPE_MAP.put("89504E","png");
            FILE_TYPE_MAP.put("474946","jif");
            FILE_TYPE_MAP.put("49492A00","tif");
            FILE_TYPE_MAP.put("424D","bmp");
            FILE_TYPE_MAP.put("41433130","dwg");
            FILE_TYPE_MAP.put("38425053","psd");
            FILE_TYPE_MAP.put("7B5C727466","rtf");
            FILE_TYPE_MAP.put("3C3F786D6C","xml");
            FILE_TYPE_MAP.put("68746D6C3E","html");
            FILE_TYPE_MAP.put("44656C69766572792D646174653A","eml");
            FILE_TYPE_MAP.put("CFAD12FEC5FD746F","dbx");
            FILE_TYPE_MAP.put("2142444E","pst");
            FILE_TYPE_MAP.put("D0CF11E0","xls.or.doc");
            FILE_TYPE_MAP.put("5374616E64617264204A","mdb");
            FILE_TYPE_MAP.put("FF575043","wpd");
            FILE_TYPE_MAP.put("252150532D41646F6265","eps.or.ps");
            FILE_TYPE_MAP.put("255044462D312E","pdf");
            FILE_TYPE_MAP.put("E3828596","pwl");
            FILE_TYPE_MAP.put("504B0304","zip");
            FILE_TYPE_MAP.put("52617221","rar");
            FILE_TYPE_MAP.put("57415645","wav");
            FILE_TYPE_MAP.put("41564920","avi");
            FILE_TYPE_MAP.put("2E7261FD","ram");
            FILE_TYPE_MAP.put("2E524D46","rm");
            FILE_TYPE_MAP.put("000001BA","mpg");
            FILE_TYPE_MAP.put("000001B3","mpg");
            FILE_TYPE_MAP.put("6D6F6F76","mov");
            FILE_TYPE_MAP.put("3026B2758E66CF11","asf");
            FILE_TYPE_MAP.put("4D546864","mid");

            FILE_TYPE_MAP.put("ffd8ffe000104a464946", "jpg"); //JPEG (jpg)
            FILE_TYPE_MAP.put("89504e470d0a1a0a0000", "png"); //PNG (png)
            FILE_TYPE_MAP.put("47494638396126026f01", "gif"); //GIF (gif)
            FILE_TYPE_MAP.put("49492a00227105008037", "tif"); //TIFF (tif)
            FILE_TYPE_MAP.put("424d228c010000000000", "bmp"); //16色位图(bmp)
            FILE_TYPE_MAP.put("424d8240090000000000", "bmp"); //24位位图(bmp)
            FILE_TYPE_MAP.put("424d8e1b030000000000", "bmp"); //256色位图(bmp)
            FILE_TYPE_MAP.put("41433130313500000000", "dwg"); //CAD (dwg)
            FILE_TYPE_MAP.put("3c21444f435459504520", "html"); //HTML (html)
            FILE_TYPE_MAP.put("3c21646f637479706520", "htm"); //HTM (htm)
            FILE_TYPE_MAP.put("48544d4c207b0d0a0942", "css"); //css
            FILE_TYPE_MAP.put("696b2e71623d696b2e71", "js"); //js
            FILE_TYPE_MAP.put("7b5c727466315c616e73", "rtf"); //Rich Text Format (rtf)
            FILE_TYPE_MAP.put("38425053000100000000", "psd"); //Photoshop (psd)
            FILE_TYPE_MAP.put("46726f6d3a203d3f6762", "eml"); //Email [Outlook Express 6] (eml)
            FILE_TYPE_MAP.put("d0cf11e0a1b11ae10000", "doc"); //MS Excel 注意：word、msi 和 excel的文件头一样
            FILE_TYPE_MAP.put("d0cf11e0a1b11ae10000", "vsd"); //Visio 绘图
            FILE_TYPE_MAP.put("5374616E64617264204A", "mdb"); //MS Access (mdb)
            FILE_TYPE_MAP.put("252150532D41646F6265", "ps");
            FILE_TYPE_MAP.put("255044462d312e360d25", "pdf"); //Adobe Acrobat (pdf)
            FILE_TYPE_MAP.put("2e524d46000000120001", "rmvb"); //rmvb/rm相同
            FILE_TYPE_MAP.put("464c5601050000000900", "flv"); //flv与f4v相同
            FILE_TYPE_MAP.put("00000020667479706973", "mp4");
            FILE_TYPE_MAP.put("49443303000000000f76", "mp3");
            FILE_TYPE_MAP.put("000001ba210001000180", "mpg"); //
            FILE_TYPE_MAP.put("3026b2758e66cf11a6d9", "wmv"); //wmv与asf相同
            FILE_TYPE_MAP.put("524946464694c9015741", "wav"); //Wave (wav)
            FILE_TYPE_MAP.put("52494646d07d60074156", "avi");
            FILE_TYPE_MAP.put("4d546864000000060001", "mid"); //MIDI (mid)
            FILE_TYPE_MAP.put("504b0304140000000800", "zip");
            FILE_TYPE_MAP.put("526172211a0700cf9073", "rar");
            FILE_TYPE_MAP.put("235468697320636f6e66", "ini");
            FILE_TYPE_MAP.put("504b03040a0000000000", "jar");
            FILE_TYPE_MAP.put("4d5a9000030000000400", "exe");//可执行文件
            FILE_TYPE_MAP.put("3c25402070616765206c", "jsp");//jsp文件
            FILE_TYPE_MAP.put("4d616e69666573742d56", "mf");//MF文件
            FILE_TYPE_MAP.put("3c3f786d6c2076657273", "xml");//xml文件
            FILE_TYPE_MAP.put("efbbbf2f2a0d0a53514c", "sql");//xml文件
            FILE_TYPE_MAP.put("7061636b616765207765", "java");//java文件
            FILE_TYPE_MAP.put("406563686f206f66660d", "bat");//bat文件
            FILE_TYPE_MAP.put("1f8b0800000000000000", "gz");//gz文件
            FILE_TYPE_MAP.put("6c6f67346a2e726f6f74", "properties");//bat文件
            FILE_TYPE_MAP.put("cafebabe0000002e0041", "class");//bat文件
            FILE_TYPE_MAP.put("49545346030000006000", "chm");//bat文件
            FILE_TYPE_MAP.put("04000000010000001300", "mxp");//bat文件
            FILE_TYPE_MAP.put("504b0304140006000800", "docx");//docx文件
            FILE_TYPE_MAP.put("d0cf11e0a1b11ae10000", "wps");//WPS文字wps、表格et、演示dps都是一样的
            FILE_TYPE_MAP.put("6431303a637265617465", "torrent");
            FILE_TYPE_MAP.put("494d4b48010100000200", "264");


            FILE_TYPE_MAP.put("6D6F6F76", "mov"); //Quicktime (mov)
            FILE_TYPE_MAP.put("FF575043", "wpd"); //WordPerfect (wpd)
            FILE_TYPE_MAP.put("CFAD12FEC5FD746F", "dbx"); //Outlook Express (dbx)
            FILE_TYPE_MAP.put("2142444E", "pst"); //Outlook (pst)
            FILE_TYPE_MAP.put("AC9EBD8F", "qdf"); //Quicken (qdf)
            FILE_TYPE_MAP.put("E3828596", "pwl"); //Windows Password (pwl)
            FILE_TYPE_MAP.put("2E7261FD", "ram"); //Real Audio (ram)
        }
    }

    public static String getFileType(MultipartFile multipartFile) throws IOException {
        InputStream is = multipartFile.getInputStream();
        is.mark(0);
        byte[] b = new byte[3];
        is.read(b);
        is.reset();
        return null;
    }

    /**
     * 获取文件类型
     * @param file
     * @return
     */
    public static String getFileType(File file){
        String res = null;
        FileInputStream fis = null;
        try{
            fis = new FileInputStream(file);
            //获取文件头的前六位
            byte[] b = new byte[3];
            fis.read(b, 0, b.length);
            String fileCode = bytesToHexString(b);
            Iterator<String> keyIter = FILE_TYPE_MAP.keySet().iterator();
            while(keyIter.hasNext()){
                String key = keyIter.next();
                //比较前几位是否相同就可以判断文件格式（相同格式文件文件头后面几位会有所变化）
                if(key.toLowerCase().startsWith(fileCode.toLowerCase()) || fileCode.toLowerCase().startsWith(key.toLowerCase())){
                    res = FILE_TYPE_MAP.get(key);
                    break;
                }
            }
            log.info("文件头:"+fileCode+"-----文件类型:"+res);
            fis.close();
        }catch(FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                fis.close();
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
        return res;
    }

    /**
     * 得到上传文件的文件头
     * @param src
     * @return
     */
    private static String bytesToHexString(byte[] src){
        StringBuilder stringBuilder = new StringBuilder();
        if(null==src || src.length <= 0){
            return null;
        }
        for(int i = 0; i < src.length; i++){
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if(hv.length() < 2){
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    public static int isRightFileExt(String ext){
        if(ext != null){
            int n = ALL_EXT.length;
            for(int i=0;i<n;i++){
                int m = ALL_EXT[i].length;
                for(int f=0;f<m;f++){
                    if(ext.equals(ALL_EXT[i][f])){
                        return i+1;
                    }
                }
            }
        }
        return -1;
    }

    public static boolean isZip(String ext){
        if(ext != null){
            ext = ext.toLowerCase();
            int n = FILE_EXT_ZIP.length;
            for(int i=0;i<n;i++){
                if(ext.equals(FILE_EXT_ZIP[i])){
                    return true;
                }
            }
        }
        return false;
    }


    public static String getExtByFileHeader(String header) {
        if(FILE_TYPE_MAP.containsKey(header)){
            return FILE_TYPE_MAP.get(header);
        }
        return null;
    }

    public static boolean isVideo(String ext){
        int n = FILE_EXT_VIDEO.length;
        for(int i=0;i<n;i++){
            if(ext.equals(FILE_EXT_VIDEO[i])){
                return true;
            }
        }
        return false;
    }

    public static boolean isAudio(String ext){
        int n = FILE_EXT_AUDIO.length;
        for(int i=0;i<n;i++){
            if(ext.equals(FILE_EXT_AUDIO[i])){
                return true;
            }
        }
        return false;
    }

    public static boolean isImage(String ext){
        int n = FILE_EXT_2D.length;
        for(int i=0;i<n;i++){
            if(ext.equals(FILE_EXT_2D[i])){
                return true;
            }
        }
        return false;
    }

    public static boolean is3DModel(String ext){
        int n = FILE_EXT_3D.length;
        for(int i=0;i<n;i++){
            if(ext.equals(FILE_EXT_3D[i])){
                return true;
            }
        }
        return false;
    }

    // 0 3D, 1 2D, 2 VIDEO, 3 AUDIO
    public static int getTypeByExt(String e){
        if(StringUtils.isBlank(e)){return -1;}
        for(int i=0,n=ALL_EXT.length;i<n;i++){
            for(String ext : ALL_EXT[i]){
                if(ext.equals(e.toLowerCase())){
                    return i;
                }
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        String a = "a.";
        System.out.println(a.substring(3));
    }
}
